package com.wx_shop.api.util.wx_mini_program;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * 微信小程序相关工具类
 */
@Component
public class MiniProgramUtil {

	private static final Logger LOG = LoggerFactory.getLogger(MiniProgramUtil.class);
		
	@Value("${wx.miniProgram.appid}")
	private String wx_appid;
	
	@Value("${wx.miniProgram.secret}")
	private String wx_secret;
	
	public LoginResEntity jscode2session(String code) {
		String url = "https://api.weixin.qq.com/sns/jscode2session?appid={wx_appid}&secret={wx_secret}&js_code={code}&grant_type=authorization_code";
		
		RestTemplate mRestTemplate = new RestTemplate();
		ResponseEntity<LoginResEntity> res = mRestTemplate.getForEntity(url, LoginResEntity.class, wx_appid, wx_secret, code);
		
		if( res.getStatusCode() == HttpStatus.OK ) {
			LoginResEntity mCommResEntity = res.getBody();
			String openid = mCommResEntity.getOpenid();
			String session_key = mCommResEntity.getSession_key();
			String unionid = mCommResEntity.getUnionid();
			
			if( StringUtils.isNotEmpty(openid) ) {
				
				LOG.error("openid={}, unionid={}, session_key={}", openid, unionid, session_key);
				
				// 存入数据库中
				return mCommResEntity;
				
			} else {
				LOG.error("errorCode={}, errmsg={}", mCommResEntity.getErrcode(), mCommResEntity.getErrmsg());
			}
			
		} else {
			
			LOG.error(" statusCode={}", res.getStatusCode().value() );
		}
		return null;
	}
	
	public static void main(String[] args) {
		// https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
	}

}
